package com.spa.infrastructure.config;

import com.spa.infrastructure.annotation.SysDictEnumAnnotation;
import com.spa.infrastructure.enums.dict.DictionaryData;
import com.spa.infrastructure.enums.dict.DictionaryManagement;
import com.spa.infrastructure.enums.dict.IBaseEnum;
import lombok.Data;
import lombok.Getter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.reflections.Reflections;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *  枚举类  字典配置
 *
 * @author: lig
 * @date: 2023年04月10日 0010
 */
@Component
@Data
public class SysDictEnumConfig implements InitializingBean {

    @Getter
    private static Map<String, DictionaryManagement> dmMap = new HashMap<>();

    public static List<DictionaryManagement> dictManageList ;

    private static void setDmMap(Map<String, DictionaryManagement> dmMap) {
        SysDictEnumConfig.dmMap = dmMap;
    }

    @Override
    public void afterPropertiesSet() {
        Reflections reflections = new Reflections("com.spa.infrastructure.enums.dict");
        Set<Class<? extends IBaseEnum>> monitorClasses = reflections.getSubTypesOf(IBaseEnum.class);
        dictManageList = new ArrayList<>();
        monitorClasses.forEach(m -> {
            if (m.isAnnotationPresent(SysDictEnumAnnotation.class)) {
                SysDictEnumAnnotation dictEnum = m.getAnnotation(SysDictEnumAnnotation.class);
                DictionaryManagement dictionaryManagement = new DictionaryManagement();
                dictionaryManagement.setDictType(dictEnum.key());
                dictionaryManagement.setDictName(dictEnum.desc());
                List<DictionaryData> ddList = new ArrayList<>();
                DictionaryData dictionaryData;
                IBaseEnum[] enumConstants = m.getEnumConstants();
                for (IBaseEnum baseEnum : enumConstants) {
                    dictionaryData = new DictionaryData();
                    dictionaryData.setDictValue(baseEnum.getCode());
                    dictionaryData.setDictTag(baseEnum.getDesc());
                    ddList.add(dictionaryData);
                }
                dictionaryManagement.setDdList(ddList);
                dictManageList.add(dictionaryManagement);
            }
        });
        setDmMap(dictManageList.stream().collect(Collectors.toMap(DictionaryManagement::getDictType, Function.identity())));
    }

}
